package com.lhj.queue;

/**
 * @ClassName Task
 * @Description 要运行的任务
 * @date 2017-03-20
 * @author hongjian.liu
 * @version 1.0.0
 *
 */
public abstract class AbstractTask implements Runnable {

	/**任务id. 如果是分布式部署多台应用，那此id要是全局唯一的*/
	private final String id;
	/**第几圈*/
	private int cycleNum;
	
	public AbstractTask(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setCycleNum(Integer cycleNum) {
		this.cycleNum = cycleNum;
	}

	public boolean canExecute(){
    	return cycleNum <= 0;
	}

	/**
	 * 	倒计数，为0时即可执行此任务
	 */
	public void countDown() {
		this.cycleNum--;
	}

	@Override
	public String toString() {
		return "Task [id=" + id + ", cycleNum=" + cycleNum + "]";
	}

	public static AbstractTask newTask(String id, Runnable runnable){
		return new RunnableTask(id, runnable);
	}

	static class RunnableTask extends AbstractTask{
		final Runnable runnable;
		public RunnableTask(String id, Runnable runnable){
			super(id);
			this.runnable = runnable;
		}
		@Override
		public void run() {
			runnable.run();
		}
	}

}
